package com.juben.svr.demos.web;

import com.juben.svr.domain.*;
import com.juben.svr.domain.Enum.Aritcle_review;
import com.juben.svr.domain.Enum.CutCap;
import com.juben.svr.domain.Enum.TypeAndtheme;
<<<<<<< HEAD
import com.juben.svr.service.HetongZujianService;
import com.juben.svr.service.TokenService;
import com.juben.svr.service.UserService;
=======
import com.juben.svr.service.TokenService;
>>>>>>> 38a1dbe3941ebf5713fbf4c6d3dbf69154c425d3
import com.juben.svr.service.UworkService;
//import com.juben.svr.service.impl.PdfServiceimpl;
import com.juben.svr.service.impl.TimeService;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:5173",allowedHeaders = "*",allowCredentials = "true")
public class UworkController {
    //static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    @Autowired
    private UworkService uworkService;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private TimeService timeService;

<<<<<<< HEAD
    @Autowired
    private HetongZujianService hetongZujianService;

=======
>>>>>>> 38a1dbe3941ebf5713fbf4c6d3dbf69154c425d3
    Transaction transaction = new Transaction();



    //@Autowired
//    private PdfServiceimpl pdfService;


    //查询剧本根据WID
    @GetMapping("/getwork/{WID}")
    public UWorks getwork(@PathVariable String WID){
        System.out.println("WID:"+WID);
        return uworkService.getworkByID(WID);
    }

    //新增剧本
   // @PostMapping("/addwork")
//    public ResponseEntity<ResponseMessage> addwork(@RequestHeader ("Authorization") String token,@RequestBody UWorks uworks){
//        System.out.println("addwork");
//        System.out.println("前端传来的user:"+uworks.toString());
//        if(uworkService.addNewWork(uworks)){
//            return ResponseEntity.ok(new ResponseMessage(200,"新增成功",token,null));
//        }else{
//            return ResponseEntity.ok(new ResponseMessage(400,"新增失败",token,null));
//        }
//    }
    //
    //
    @PostMapping("/addwork")
    public ResponseEntity<ApiResponse> insertUWorks(@RequestHeader("Authorization") String token,@RequestBody UWorks uWorks){
        System.out.println("addwork");
        System.out.println("前端传来的:"+uWorks);
        System.out.println("前端传来的token:"+token);
        if (token == null || !token.startsWith("Bearer ")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new ApiResponse(401, "无效的令牌", null));
        }
        token = token.substring(7); // 删除 "Bearer " 前缀
        System.out.println("删除前缀后："+token);
        // 验证令牌并解析用户 ID
        System.out.println("开始解析用户id");
        Integer userId;
        try {
            userId = tokenService.getUserIdFromToken(token);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(401, "无效令牌或已过期", null));
        }

        System.out.println("userId:"+userId);
        //修改剧本实体类的用户id
        uWorks.setUID(userId);
        System.out.println("修改后的实体类:"+uWorks);
        boolean result = uworkService.createUWorks(uWorks);
        if (result) {
            // 返回成功的状态码和消息
            return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse(200, "剧本创建成功", null));
        } else {
            // 返回失败的状态码和消息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse(400 , "剧本创建失败", null));
        }
    }

    //查询剧本所有类型接口
    @GetMapping("/getworktype")
    public ResponseEntity<ApiResponse> getAllTypes(){
        List<jb_types> types = uworkService.getTypeList();
        return ResponseEntity.ok(new ApiResponse(200,"查询成功",types));
    }
    //查询所有标签（题材）
    @GetMapping("/getworklabel")
    public ResponseEntity<ApiResponse> getAllLabels(){
        List<Label> labels = uworkService.getLabelList();
        System.out.println(labels);
        return ResponseEntity.ok(new ApiResponse(200,"查询成功",labels));
    }

    //查询剧本的题材列表
    @GetMapping("/getworklabelByWid/{WID}")
    public ResponseEntity<ApiResponse> getLabelList(@PathVariable String WID){
        System.out.println("getLabelList");
        System.out.println("WID:"+WID);
        List<Label> labels = uworkService.getLabelIdsByWID(WID);
        System.out.println("labels:"+labels);
        return ResponseEntity.ok(new ApiResponse(200,"查询成功",labels));
    }

    //查询剧本类型（themeId)
    @GetMapping("/getworktypeByThemeId/{themeId}")
    public ResponseEntity<ApiResponse> getTypeList(@PathVariable Integer themeId){
        System.out.println("getTypeList");
        System.out.println("themeId:"+themeId);
        String type = uworkService.getTypeNameByID(themeId);
        System.out.println("type:"+type);
        return ResponseEntity.ok(new ApiResponse(200,"查询成功",type));
    }

    @PostMapping("/getworklistByUID")
    public ResponseEntity<ApiResponse> getWorkListByUID(@RequestHeader("Authorization") String token) {
        System.out.println("getWorkListByUID");
        System.out.println("token: " + token);

        try {
            // 删除 "Bearer " 前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            } else {
                // 如果没有 Bearer 前缀，返回错误响应
                return ResponseEntity
                        .status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse(401, "无效的授权 token", null));
            }

            Integer userId = tokenService.getUserIdFromToken(token);
            if (userId == null) {
                // 如果无法从 token 获取到 userId，返回错误响应
                return ResponseEntity
                        .status(HttpStatus.UNAUTHORIZED)
                        .body(new ApiResponse(401, "无效的授权 token", null));
            }

            List<UWorks> uWorksList = uworkService.getUWorksByUID(userId);
            if (uWorksList == null || uWorksList.isEmpty()) {
                return ResponseEntity
                        .status(HttpStatus.NOT_FOUND)
                        .body(new ApiResponse(404, "无工作列表", null));
            }

            return ResponseEntity.ok(new ApiResponse(200, "查询成功", uWorksList));

        } catch (Exception e) {
            // 处理其它可能的异常
            e.printStackTrace(); // 记录错误到控制台或日志
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(500, "服务器内部错误: " + e.getMessage(), null));
        }
    }

    // 修改剧本内容
    @PostMapping("/updateworkByWrite")
    public ResponseEntity<ApiResponse> updateUWorks(@RequestBody UWorks uWorks){
        System.out.println("updateworkByWrite_____________________________");
        System.out.println("前端传来的:"+uWorks);
        if (uWorks.getRelease_time() == null){
            String release_time = timeService.getCurrentDateTime();
            uWorks.setRelease_time(release_time);
        }

        boolean result = uworkService.updateUWorks(uWorks);
        if (result) {
            // 返回成功的状态码和消息
            return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse(200, "修改成功", null));
        } else {
            // 返回失败的状态码和消息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse(400 , "修改失败", null));
        }
    }

    //对剧本内容进行审核
    @PostMapping("/updateworkByReview")
    public Object updateUWorksByReview(@RequestBody UWorks uWorks){
        System.out.println("updateworkByReview_____________________________");
        System.out.println(uWorks.getWddata());
        CutCap cutCap = new CutCap();
        String cap = cutCap.catchCap(uWorks.getWddata());
        System.out.println("去掉标签后的剧本内容："+cap);
        System.out.println("进行智能审核===》");
        Aritcle_review aritcle_review = new Aritcle_review();
        Object s = null;
        try {
             s = aritcle_review.shenhe(cap);
            System.out.println("只能审核结果："+s);
        } catch (IOException e) {
            // 打印异常信息到控制台
            System.err.println("发生了一个I/O错误：" + e.getMessage());
            // 可以在这里添加更多的错误处理逻辑，比如记录日志、重试等
        }
       return ResponseEntity.ok(s);
    }

    //修改剧本合同内容
    @PostMapping("/updateworkByContract")
    public ResponseEntity<ApiResponse> updateUWorksByContract(@RequestBody UWorks uWorks){
        System.out.println("updateUWorksByContract");
        System.out.println("前端传来的："+uWorks);
        boolean result = uworkService.updateUWorksByContract(uWorks);
        if (result) {
            // 返回成功的状态码和消息
            return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse(200, "修改成功",null));
        }else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse(400, "修改失败",null));
        }
    }

    //通过剧本类型查询剧本列表
    @GetMapping("/getworklist")
    public ResponseEntity<ApiResponse> getWorkList(){
        //查询剧本类型列表
        List<jb_types> jb_types = uworkService.getTypeList();

        // 用于存储所有类型的剧本响应
        List<getWordResponse> responseList = new ArrayList<>();
        for (jb_types jb_type : jb_types) {
            //循环列表查询同类型剧本列表
            List<UWorks> uWorksList = uworkService.getUWorkListByTypeId(jb_type.getThemeID());
            System.out.println("uWorks:==================="+uWorksList);
            // 创建获取剧本的响应对象并填充信息
            getWordResponse getWordResponse = new getWordResponse();
//            List<UWorks> uWorksList = new ArrayList<>(uWorks);  // 将查询结果添加到集合中
            System.out.println("uWorksList:"+uWorksList);
            getWordResponse.setTid(jb_type.getThemeID());
            getWordResponse.setTypename(jb_type.getThemename());
            getWordResponse.setData(uWorksList); // 将当前类型的剧本列表设置到响应对象中
            // 将响应对象添加到响应列表中
            responseList.add(getWordResponse);
        }
//        getWordResponse.setData(data);
        System.out.println("查询结果(循环外）："+responseList);
        return ResponseEntity.ok(new ApiResponse(200, "查询成功", responseList));
    }

    //通过剧本类型和剧本题材查询剧本列表
    @PostMapping("/getWorkByfenleiList")
    public ResponseEntity<ApiResponse> getWordResponse(@RequestBody TypeAndtheme typeAndtheme){
        System.out.println("getWorkByfenleiList_____________________________");
        System.out.println("前端传来的："+typeAndtheme);
        List<UWorks> uWorksList = uworkService.getUWorkList(typeAndtheme);
        System.out.println("查询结果："+uWorksList);
        return ResponseEntity.ok(new ApiResponse(200, "查询成功", uWorksList));

    }

    //根据剧本名称进行模糊搜索
    @GetMapping("/getworklistByName")
    public ResponseEntity<ApiResponse> getWorkListByName(@RequestParam String Wname){
        System.out.println("getWorkListByName_____________________________");
        System.out.println("前端传来的："+Wname);
        List<UWorks> uWorksList = uworkService.getUWorkListByWName(Wname);
        System.out.println("查询结果："+uWorksList);
        return ResponseEntity.ok(new ApiResponse(200, "查询成功", uWorksList));
    }
//    新建的合同（初始化合同）
    @PostMapping("/newTransaction")
    public ResponseEntity<ApiResponse> insertTransaction(@RequestBody UWorks uWorks,@RequestHeader("Authorization") String token){
        System.out.println("insertTransaction");
        System.out.println("获取到的uWorks:"+uWorks);
        System.out.println("获取到的token:"+token);
        //前置条件，查询这个剧本双方是否已经存在合同，并且合同并未完成(版权方、用户、剧本）


        //解析token
        // 删除 "Bearer " 前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌1111",  null));
        }
        try {
            // 获取登录用户id
            Integer userId = tokenService.getUserIdFromToken(token);
            //判断登录用户是否为版权方
            if (userId.equals(uWorks.getUID())){
                return ResponseEntity.status(200).body(new ApiResponse(401, "版权方不能创建合同",  null));
            }else {
                //查询是否
                //将初始化数据写入对象
                transaction.setLicensee_id(userId);
            }
            transaction.setWid(uWorks.getWID());
            //获取当前日期
            String nowDate = timeService.getCurrentDateTime();
            transaction.setTransaction_date(nowDate);
            transaction.setOwnerId(uWorks.getUID());
            transaction.setTransaction_amount(uWorks.getAuthorization_fee());
            transaction.setTime(uWorks.getTime());
            transaction.setPlatform(uWorks.getPlatform());
            transaction.setAge_limit(uWorks.getAge_limit());
            //前置条件，查询这个剧本双方是否已经存在合同，并且合同并未完成(版权方、用户、剧本）
            if (uworkService.TransactionExite(transaction)){
                return ResponseEntity.status(200).body(new ApiResponse(401, "合同已存在",  null));
            }else {
                //增加合同记录
                System.out.println("transaction:" + transaction);
                Boolean i = uworkService.insertTransaction(transaction);
                System.out.println("添加:" + i);
                return ResponseEntity.ok(new ApiResponse(200, "添加成功", null));
            }
        }catch (Exception e){
            System.out.println(e);
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌2222",  null));
        }
    }

    //获取剧本合同
    @PostMapping("/getTransaction")
    public ResponseEntity<ApiResponse> getTransaction(@RequestBody UWorks uWorks,@RequestHeader("Authorization") String token){
        System.out.println("getTransaction=========");
        System.out.println("获取到的uWorks:"+uWorks);
        System.out.println("获取到的token:"+token);
        //解析token
        // 删除 "Bearer " 前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌1111",  null));
        }
        try {
            Integer userId;
            try {
                userId = tokenService.getUserIdFromToken(token);
            }catch (Exception e){
                return ResponseEntity.status(200).body(new ApiResponse(401, "令牌已过期",  null));
            }
            //将初始化数据写入对象
            //判断获取的用户id是不是版权方
            if(userId.equals(uWorks.getUID())){
                transaction.setOwnerId(userId);
            }else {
                transaction.setLicensee_id(userId);
            }

            transaction.setWid(uWorks.getWID());
            System.out.println("transaction:" + transaction);
            Transaction transaction1 = uworkService.getTransaction(transaction);
            System.out.println("查询结果："+transaction1);
            return ResponseEntity.ok(new ApiResponse(200, "查询成功", transaction1));
        }catch (Exception e){
            return ResponseEntity.status(200).body(new ApiResponse(401, "出现错误",  null));
        }
    }

    //修改交易合同信息
    @PostMapping("/setTransaction")
    public ResponseEntity<ApiResponse> setTransaction(@RequestBody Transaction transaction,@RequestHeader("Authorization") String token){
        System.out.println("setTransaction=========");
        System.out.println("获取到的transaction:"+transaction);
        System.out.println("获取到的token:"+token);
        //解析token并获取id
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌",  null));
        }
        try {
            Integer userId = tokenService.getUserIdFromToken(token);
            if (userId != null){
                boolean isKeys = uworkService.setTransaction(transaction);
                if (isKeys){
                    return ResponseEntity.ok(new ApiResponse(200, "修改成功", null));
                }else {
                    return ResponseEntity.status(200).body(new ApiResponse(401, "修改失败",  null));
                }
            }
            return ResponseEntity.status(200).body(new ApiResponse(401, "令牌过期",  null));
        }catch (Exception e){
            System.out.println(e);
            return ResponseEntity.status(200).body(new ApiResponse(401, "令牌过期",  null));
        }
    }

    //添加数字签名和时间
    @PostMapping("/setPartyAndTime")
    public ResponseEntity<ApiResponse> setPartyAndTime(@RequestBody Transaction transaction,@RequestHeader("Authorization") String token){
        System.out.println("setPartyAndTime=========");
        System.out.println("获取到的transaction:"+transaction);
        System.out.println("获取到的token:"+token);
        //解析token并获取id
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌1111",  null));
        }
        try {
            Integer userId = tokenService.getUserIdFromToken(token);
            //判断获取到的用户是不是transaction中的剧本所有者
            if (userId.equals(transaction.getOwnerId())){
                //如果是，那么获取到的用户id赋值给OwnerId；
                transaction.setOwnerId(userId);
                transaction.setFlow("3");
                System.out.println("transaction:" + transaction);
                return ResponseEntity.ok(new ApiResponse(200, "版权所有者签名成功", uworkService.setPartyAndTime(transaction)));
            }else {
                //如果不是，获取到的id赋值给licensee_id
                transaction.setLicensee_id(userId);
                transaction.setFlow("2");
                System.out.println("transaction:" + transaction);
                Boolean i = uworkService.setPartyAndTime(transaction);
                if (i) {
                    return ResponseEntity.status(200).body(new ApiResponse(200, "用户签名成功", uworkService.setPartyAndTime(transaction)));
                }else {
                    return ResponseEntity.status(200).body(new ApiResponse(200, "用户签名失败", uworkService.setPartyAndTime(transaction)));
                }
            }
        }
        catch (Exception e){
            System.out.println(e);
            return ResponseEntity.status(200).body(new ApiResponse(401, "令牌已过期",  null));
        }
    }

<<<<<<< HEAD
    //增加合同组件信息记录
    @PostMapping("/addworkzujian")
    public ResponseEntity<ApiResponse> addworkzujian(@RequestBody HetongZujian hetongZujian,@RequestHeader("Authorization") String token) {
        System.out.println("addworkzujian=========");
        System.out.println("获取到的hetongZujian:" + hetongZujian);
        System.out.println("获取到的token:" + token);
        //解析token并获取id
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        } else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌1111", null));
        }
        //验证令牌并解析用户 ID
        try {
            Integer userId = tokenService.getUserIdFromToken(token);
            hetongZujian.setUser_id(userId);
        }catch (Exception e){
            return ResponseEntity.status(200).body(new ApiResponse(401, "令牌已过期", null));
        }
        System.out.println("hetongZujian:" + hetongZujian);
        //增加一条记录
        boolean result = hetongZujianService.insertHeTongZujian(hetongZujian);
        if (result){
            return ResponseEntity.ok(new ApiResponse(200, "增加成功", null));
        }else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "增加失败", null));
        }

    }

    //查询剧本组件信息
    @PostMapping("/getHetongZujian")
    public ResponseEntity<ApiResponse> getHetongZujian(@RequestBody HetongZujian hetongZujian,@RequestHeader("Authorization") String token) {
        System.out.println("getHetongZujian=========");
        System.out.println("获取到的WID值:" + hetongZujian);
        System.out.println("获取到的token:" + token);
        //解析token并获取id
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        } else {
            return ResponseEntity.status(200).body(new ApiResponse(401, "无效的令牌222", null));
        }
        //验证令牌并解析用户 ID
        try {
            Integer userId = tokenService.getUserIdFromToken(token);
            System.out.println("userId:"+userId);
            hetongZujian.setUser_id(userId);
            System.out.println("hetongZujian:"+hetongZujian);
            HetongZujian hetongZujian2 = hetongZujianService.getHetongZujian(hetongZujian);
            System.out.println("hetongZujian2:"+hetongZujian2);
            return ResponseEntity.ok(new ApiResponse(200, "查询成功", hetongZujian2));
        }catch (Exception e){
            System.out.println(e);
            return ResponseEntity.status(200).body(new ApiResponse(401, "令牌已过期", null));
        }

    }


=======
>>>>>>> 38a1dbe3941ebf5713fbf4c6d3dbf69154c425d3
}
